import { FetchRawDataFailHandler } from "./error/fetchRawDataFailHandler.js";
import { myLogger } from "../logger/myLogger/mylogger";
import { ParseDataExceptionHandler } from "./error/parseDataExceptionHandler.js";
import { ConnectKafkaErrorHandler } from "./error/connectKafkaErrorHandler.js";
import { ParseConfErrorHandler } from "./error/parseConfErrorHandler.js";
import { ParseReqExceptionHandler } from "./error/parseReqError.js";
const enum EventCode {
    NORMAL = 0,

    //error_code
    FETCH_RAW_DATA_FAIL = 400,
    PAESE_RAW_DATA_EXCEPTION,

    //connect_error
    CONNECT_KAFKA_ERROR = 500,

    //parseConfErr
    PARSE_CONF_ERROR=700,

    PAESE_REQ_ERROR=800

}


interface IExcepHandler {
    handle(logger: myLogger, code: EventCode, info: string, msg?: Error): void;
    nextHandle: IExcepHandler | null;
}

class EventHandler {
    private static logger: myLogger
    private static _instance: EventHandler = new EventHandler();
    public static getInstance(): EventHandler {
        return this._instance;
    }
    public static setLogger(logger: myLogger) {
        this.logger = logger
    }

    private headlerHead: IExcepHandler | null = null;
    private headlerTitle: IExcepHandler | null = null;

    public handle(code: EventCode, info: string, msg?: Error) {
        if (code === EventCode.NORMAL) {
            EventHandler.logger.log(info)
            return
        }
        if (this.headlerHead != null) {
            this.headlerHead.handle(EventHandler.logger, code, info, msg);
        }
    }
    public close() :Promise<void>{
        return EventHandler.logger.close()
    }

    public appendHandler(handler: IExcepHandler): EventHandler {
        if (this.headlerHead == null) {
            this.headlerHead = handler;
            this.headlerTitle = handler;
            return this;
        }
        (this.headlerTitle as IExcepHandler).nextHandle = handler;
        this.headlerTitle = handler;
        return this
    }
}

let eventHandler = EventHandler.getInstance()
eventHandler.appendHandler(new ParseDataExceptionHandler())
    .appendHandler(new FetchRawDataFailHandler())
    .appendHandler(new ConnectKafkaErrorHandler())
    .appendHandler(new ParseConfErrorHandler())
    .appendHandler(new ParseReqExceptionHandler())
export { EventCode, IExcepHandler, eventHandler, EventHandler }